/**
 * Created by Xiaoming on 2017/8/30.
 */
angular.module('module.wxauth')
    .controller('WxJumpController', WxJumpController);
WxJumpController.$inject = ['$state', 'WxAuthService', 'UserinfoService'];
function WxJumpController($state, WxAuthService, UserinfoService) {
    var vm = this;
    vm.wxGetOpenid = wxGetOpenid;
    vm.wxLoginOpenid = wxLoginOpenid;
    vm.wxLoginJump = wxLoginJump;
    vm.appid = mall_userauth.wxmp_appid;
    var wxopenid = WxAuthService.getOpenid();
    if (wxopenid && wxopenid.$promise) {
        wxopenid.$promise.then(function (openid) {
            //alert(JSON.stringify(openid));
            vm.openid = openid.openid;
        }, function (error) {
            alert(JSON.stringify(error));
        });
    } else {
        vm.openid = wxopenid;
    }
    // 微信授权获取Openid
    function wxGetOpenid() {
        var redirect_uri = window.location.href;
        //alert(redirect_uri);
        //
        WxAuthService.wxOpenidJump(redirect_uri);
    }
    // 微信openid登陆获取用户信息
    function wxLoginOpenid() {
        UserinfoService.getUserinfoByOpenid(mall_userauth.wxmp_appid, vm.openid).$promise.then(function (userinfo) {
            vm.userinfo = userinfo;
        }, function (error) {
            alert(JSON.stringify(error));
        });
    }
    // 微信登录
    function wxLoginJump() {
        var redirect_uri = window.location.href.replace("/wxjump", "/wxuc");
        alert(redirect_uri);
        function success_cbfunc(userinfo) {
            alert("success_cbfunc userinfo="+JSON.stringify(userinfo));
            setCookie('_userName', userinfo.nickname, 60);
            setCookie('_userId', userinfo.userid, 60);
            if (userinfo.logo) {
                setCookie('_userLogo', userinfo.logo, 60);
            } else {
                delCookie('_userLogo');
            }
            $state.go("wxuc");
            // setTimeout(function () {
            //     $window.history.back();
            // }, 500);
        }
        function error_cbfunc(error, openid) {
            alert(JSON.stringify(error));
            alert(openid);
        }
        //
        WxAuthService.wxTryLoginOrRegist(redirect_uri, UserinfoService.getUserinfoByOpenid, success_cbfunc, error_cbfunc);
    }
}